package com.eunion.boot.security;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.eunion.boot.spring.LocaleMessageSourceService;
import com.eunion.boot.spring.SpringUtil;
import com.eunion.core.LogUtil;
import com.eunion.common.util.CommUtils;

/**
 * 自定义登录验证方式.
 * 
 * @since 2017年1月1日
 */
@Component
public class SysAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private SysUserDetailsService sysUserDetailsService;

	/**
	 * 自定义验证方式
	 */
	@Override
	public Authentication authenticate(Authentication authentication)
	    throws AuthenticationException {
		SysWebAuthenticationDetails details = (SysWebAuthenticationDetails) authentication.getDetails(); // 如上面的介绍，这里通过authentication.getDetails()获取详细信息
		// System.out.println(details); details.getRemoteAddress(); details.getSessionId(); details.getToken();
		LogUtil.get(this.getClass()).info("vCode:{},sessionId:{},remoteAdd:{}", details.getVarifyMsg(), details.getSessionId(), details.getRemoteAddress());
		if (StringUtils.isNotEmpty(details.getVarifyMsg())) {
			throw new BadCredentialsException(details.getVarifyMsg());
		}

		String username = authentication.getName();
		String password = (String) authentication.getCredentials();
		SysUserDetails user = (SysUserDetails) sysUserDetailsService.loadUserByUsername(username);
		
		String errorMsg = null; // 合并不同的错误场景
		if (user == null) {
			errorMsg = "sys.login.userNotExist";// 用户不存在
		} else if (user.getStatus() <= 0) {
			errorMsg = "sys.login.userDisabled";// 用户被禁用
		} else if (!CommUtils.getMd5(password).toUpperCase().equalsIgnoreCase(user.getPassword())) {
			errorMsg = "sys.login.passwordError";// 密码错误
		}
		// 检查
		if (StringUtils.isNotBlank(errorMsg)) {
			LocaleMessageSourceService localeMessageSourceService = SpringUtil.getBean(LocaleMessageSourceService.class);
			String varifyMsg = localeMessageSourceService.getMessage(details.getRequest(), errorMsg);
			throw new BadCredentialsException(varifyMsg);
		}

		Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
		return new UsernamePasswordAuthenticationToken(user, password, authorities);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
